package com.atguigu.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.MemberVo;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.feign.CouponFeignService;
import com.atguigu.gulimall.seckill.feign.ProductFeignService;
import com.atguigu.gulimall.seckill.vo.SeckillSessionsWithSkus;
import com.atguigu.gulimall.seckill.vo.SeckillSkuRedisTo;
import com.atguigu.gulimall.seckill.vo.SeckillSkuRelationVo;
import com.atguigu.gulimall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.atguigu.gulimall.seckill.interceptor.LoginUserInterceptor.loginUser;

@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";

    private final String SKUKILL_CACHE_PREFIX = "seckill:skus:";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:"; //+商品随机码

    @Override
    public String kill(String killId, String key, Integer num) {

        long methodStartTime = System.currentTimeMillis();

        //随机码和秒杀商品对应关系校验
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String s = hashOps.get(killId.replace("-", "_"));
        if (StringUtils.isEmpty(s)){
            return null;
        }

        SeckillSkuRedisTo redisTo = JSON.parseObject(s, SeckillSkuRedisTo.class);
        if(!StringUtils.equals(key,redisTo.getRandomCode())){
            return null;
        }

        //判断当前是否在秒杀时间内
        Long endTime = redisTo.getEndTime();
        Long startTime = redisTo.getStartTime();
        long nowTime = new Date().getTime();
        if (nowTime < startTime || nowTime > endTime){
            return null;
        }

        //超过限购份额
        if (num > redisTo.getSeckillLimit().intValue()){
            return null;
        }

        //幂等性 每个人只能每个场次的每个商品只能购买一次
        MemberVo memberVo = loginUser.get();
        String userId = memberVo.getId()+"";
        String redisKey = userId+"_"+redisTo.getPromotionSessionId()+"_"+redisTo.getSkuId();
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(),endTime-nowTime, TimeUnit.MILLISECONDS);
        if (!flag){
            //已经买过了
            return null;
        }

        //信号量判断
        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + key);
        boolean b = semaphore.tryAcquire(num); //尝试获取信号量
        if (!b){
            //获取不到信号量，直接快速返回null
            return null;
        }

        String timeId = IdWorker.getTimeId();//生成订单号

        //给MQ发个创建订单的消息
        SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
        seckillOrderTo.setOrderSn(timeId);
        seckillOrderTo.setNum(num);
        seckillOrderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
        seckillOrderTo.setSeckillPrice(redisTo.getSeckillPrice());
        seckillOrderTo.setSkuId(redisTo.getSkuId());
        seckillOrderTo.setMemberId(memberVo.getId());
        rabbitTemplate.convertAndSend("order-event-exchange",
                "order.seckill.order",
                seckillOrderTo);

        long methodEndTime = System.currentTimeMillis();
        System.out.println("耗时"+(methodEndTime-methodStartTime)+"毫秒");
        return timeId;
    }

    @Override
    public List<SeckillSkuRedisTo> getSeckillSkuInfo(Long skuId) {
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();

        ArrayList<SeckillSkuRedisTo> list = new ArrayList<>();

        if(keys == null){
            return list;
        }

        for (String key : keys) {
            String regex = "\\d_" + skuId;
            if (key.matches(regex)){
                String s = hashOps.get(key);
                SeckillSkuRedisTo redisTo = JSON.parseObject(s, SeckillSkuRedisTo.class);
                //一个商品可能参与多个场次的秒杀，所以循环中可能存在多个匹配的结果，应该全部收集起来返回
                //只显示秒杀时间还没结束的场次，并且还没开始的场次不应该返回randomCode
                long nowTime = new Date().getTime();
                if (nowTime <= redisTo.getStartTime()){
                    redisTo.setRandomCode(null);
                    list.add(redisTo);
                }else if (nowTime <= redisTo.getEndTime()){
                    list.add(redisTo);
                }else{
                    //秒杀时间已经结束的，不返回
                }
            }
        }

        return list;
    }

    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        long nowTime = new Date().getTime();
        Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        if (keys != null){
            for (String key : keys) {
                String startEnd = key.replace(SESSIONS_CACHE_PREFIX, "");
                String[] split = startEnd.split("_");
                long start = Long.parseLong(split[0]);
                long end = Long.parseLong(split[1]);
                if (nowTime >= start && nowTime <= end){
                    List<String> seckillSkus = redisTemplate.opsForList().range(key, 0, -1);//从零开始到-1表示取出全部
                    /*BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                    List<Object> seckillSkuObjects= seckillSkus.stream().map(item -> (Object) item).collect(Collectors.toList());*/
                    BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                    List<String> list = hashOps.multiGet(seckillSkus);
                    if (list != null){
                        List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                            SeckillSkuRedisTo redisTo = JSON.parseObject(item, SeckillSkuRedisTo.class);
                            //这里是已经开始了，所以随机码也不用屏蔽了；但如果是预告，随机码应该屏蔽掉
                            return redisTo;
                        }).collect(Collectors.toList());
                        return collect; //业务上预设一个时间段只会有一个秒杀场次（里面商品可以有很多），所以找到了就不用遍历后面的了
                    }
                    break; //业务上预设一个时间段只会有一个秒杀场次（里面商品可以有很多），所以找到了就不用遍历后面的了
                }
            }
        }
        return null;
    }

    /**
     * TODO 上架的时候要秒杀的商品应该提前锁定好相应库存；秒杀活动结束后如果还有没卖完的，再加回去
     */
    @Override
    public void upLast3DaysSeckillProduct() {
        R r = couponFeignService.getLast3DaysSecKillSession();
        if (r.getCode() == 0){
            List<SeckillSessionsWithSkus> sessions = r.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
            });
            cacheSeckillSessionInfo(sessions);
            cacheSeckillSessionSku(sessions);

            System.out.println("商品上架成功");
        }
    }

    private void cacheSeckillSessionInfo(List<SeckillSessionsWithSkus> list) {
        list.stream().forEach(session->{
            Long startTime = session.getStartTime().getTime();
            Long endTime = session.getEndTime().getTime();
            String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;

            //如果key存在则不操作，保证幂等性
            if (!redisTemplate.hasKey(key)){
                List<String> collect = session.getRelationSkus().stream()
                        .map(sku -> sku.getPromotionSessionId()+"_"+sku.getSkuId()).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key,collect);
            }
        });
    }

    private void cacheSeckillSessionSku(List<SeckillSessionsWithSkus> list) {
        list.stream().forEach(session->{
            BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            List<SeckillSkuRelationVo> relationSkus = session.getRelationSkus();
            relationSkus.stream().forEach(item->{

                String randomCode = UUID.randomUUID().toString().replaceAll("-", "");

                //保证幂等，已经有了这个key就不动了
                //TODO 但是hash的方式就算重复保存同一个key也没事吧
                if (!hashOps.hasKey(item.getPromotionSessionId()+"_"+ item.getSkuId())){
                    SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                    //1、商品的基本数据
                    //TODO 这里在两个循环里查库，后续需要优化
                    R r = productFeignService.skuInfo(item.getSkuId());
                    if (r.getCode() == 0 ){
                        SkuInfoVo skuInfoVo = r.getData(new TypeReference<SkuInfoVo>() {
                        },"skuInfo");
                        System.out.println("=========================================");
                        System.out.println("skuInfoVo:"+skuInfoVo);
                        redisTo.setSkuInfo(skuInfoVo);
                    }else{
                        throw new RuntimeException("获取秒杀商品sku信息失败");
                    }

                    //2、商品的秒杀数据
                    BeanUtils.copyProperties(item,redisTo);

                    //3、商品的秒杀时间
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());

                    //4、随机码
                    redisTo.setRandomCode(randomCode);

                    String s = JSON.toJSONString(redisTo);
                    hashOps.put(item.getPromotionSessionId()+"_"+ item.getSkuId(),s);

                    //5、以参与秒杀的商品的数量作为分布式信号量 只有成功获得信号量的人才会执行后续逻辑，否则快速返回秒杀失败的结果
                    //通过信号量来起到一个限流的作用，这是非常核心的一个步骤
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                    semaphore.trySetPermits(item.getSeckillCount().intValue());
                }






            });
        });
    }
}
